﻿# Author: Yunqiao Zhang, Nemo, jumpingzp
# Email: zhangyunqiao@gmail.com, nemo.zhp@gmail.com, jumpingzp@gmail.com

from django.contrib.auth.decorators import login_required
from django.contrib import auth
from django.utils import simplejson
from django.db.models import permalink
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import loader, Context, RequestContext
from datetime import datetime, date, time

from util import async_send_mail

from meet001.meetup.forms import MeetupCreateForm
from meet001.meetup.models import Membership, Group, Meetup, JoinMeetup

MEETUP_CREATE_EMAIL_SUBJECT = u'有新碰头啦'
MEETUP_UPDATE_EMAIL_SUBJECT = u'碰头信息更新啦'
MEETUP_CREATE_EMAIL_FROM_ADDRESS = 'admin@pengtouba.cn'
MEETUP_UPDATE_EMAIL_FROM_ADDRESS = 'pengtouba@gmail.com'

# handle /group/<group_id>/meetup/create
@login_required
def create(request, group_id):
  # Check if this user is the admin of this group.
  # Only Admin has permission to add meetup.
  group = Group.objects.get(pk=group_id)
  if group.creator != request.user:
    return HttpResponse('No permission to create Meetup for this group')

  if request.method == "POST":
    form = MeetupCreateForm(request.POST)
    if form.is_valid():
      meetup_id = form.save(group)
      # Send notification mail to each group member
      meetup = Meetup.objects.get(pk=meetup_id)
      url = request.build_absolute_uri(get_meetup_detail_url(group.id, meetup.id))
      send_meetup_create_notification(group, meetup, url)
      # Should redirect to meetup detail page later
      return HttpResponseRedirect('/group/' + str(group_id) 
              + '/meetup/details/' + str(meetup_id)  + '/')
    else:
      return render_to_response(
        'meetup_meetup_create.html',
        {'form': form},
        context_instance = RequestContext(request))
  else:
    form = MeetupCreateForm()
    return render_to_response(
        'meetup_meetup_create.html', 
        {'form': form},
        context_instance = RequestContext(request))

def details(request,meetup_id, group_id):
#def details(request):
  #Currently joined just have two value, actual value may have 3.
  #Stands for: Requested, Approved, Processing. Now just use a boolean.
  
  if request.method == 'POST':
      #used twice to access db, once before updating, once after, is there any efficient way?
    meetup = Meetup.objects.get(pk=meetup_id)
    old_topic = meetup.topic
    upd_dict=update(request, meetup_id)
    if 'notify_others' in request.POST and request.POST['notify_others'] == u'true':
      url = request.build_absolute_uri(get_meetup_detail_url(group_id, meetup_id))
      send_meetup_update_notification(Group.objects.get(pk=group_id), 
                                     Meetup.objects.get(pk=meetup_id), old_topic,url)
    
    return HttpResponse(simplejson.dumps(upd_dict), mimetype='application/javascript')

# if not, show the 
  joined = False
  anonymous = True
  status = -1
  pasted = False
  if not request.user.is_anonymous():
    anonymous = False
  #find whether the meetup exist
  group = Group.objects.get(id=group_id)
  meetups = Meetup.objects.filter(id=meetup_id, group=group_id)
  #if exist
  if meetups:
#    if request.user in meetups[0]
    meetup = meetups[0]
    
    definite_users = []
    refused_users = []
    undecided_users = []
    
    #judge whether the user is the group creator
    
    for group_user in group.users.all():
      if request.user == group_user:
        joined = True

      joinMeetups = JoinMeetup.objects.filter(user = group_user, meetup = meetup).all()
      if joinMeetups:
        if request.user == group_user:
          status = joinMeetups[0].join_status
        if joinMeetups[0].join_status == 0:
          definite_users.append(group_user)
        else: 
          refused_users.append(group_user)
      else:
        undecided_users.append(group_user)

    #check whether the meetup is a past meetup
    now = datetime.now()
    if meetups[0].time_from < now:
      pasted = True
    #display it
    return render_to_response('meetup_meetup_details.html',
                              {'meetup':meetups[0], 
                               'anonymous':anonymous,
                               'joined':joined,
                               'status':status,
                               'definite_users': definite_users,
                               'undecided_users': undecided_users,
                               'refused_users': refused_users,
                               'user':request.user,
                               'creator':(group.creator == request.user),
                               'pasted':pasted})
  else:
    #if not exist, check whether current user is the creator
    group = Group.objects.filter(id=group_id)[0]
    if group.creator != request.user:
      return HttpResponse('''Sorry, the meetup infomation you requested does not exist\
      you can create infomation in your own group''')
#    group_id = meetups[0].group.id
    return HttpResponseRedirect('/group/%s/meetup/create' %group_id)
  
  
def participate(request, group_id):
  if request.method == "POST":
    user = request.user
    meetup = Meetup.objects.get(id=request.POST['meetup_id'])
    group = Group.objects.get(pk=group_id)

    # validate this user is in this group.
    if not user in group.users.all():
      return HttpResponseRedirect('/group/%s/meetup/details/%s' %(group_id,meetup.id))

    jm = None
    try:
      jm = JoinMeetup.objects.get(meetup = meetup, user = user)
    except:
      # if JoinMeetup doesn't exist create 1 for this user.
      jm = JoinMeetup()
      jm.user = user
      jm.meetup = meetup
    if cmp(request.POST['response'], u'1') == 0:
      jm.join_status = 0
      jm.save()
      #after join, go to the group_details page
      return HttpResponseRedirect('/group/%s/meetup/details/%s' %(group_id,meetup.id))
    elif cmp(request.POST['response'], u'2') == 0:
      jm.join_status = 1
      jm.save()
      return HttpResponseRedirect('/group/%s/meetup/details/%s' %(group_id,meetup.id))
    else:
      return HttpResponseRedirect('/group/%s/meetup/details/%s' %(group_id,meetup.id))
  
def cancel_join(request, group_id):
  if request.method == "POST":
    user_ref = request.user
    meetup_ref = Meetup.objects.get(id=request.POST['meetup_id'])
    try:
      joinMeetup = JoinMeetup.objects.get(user=user_ref, meetup=meetup_ref)
      if joinMeetup:
        joinMeetup.delete()
    except:
      pass
    return HttpResponseRedirect('/group/%s/meetup/details/%s' %(group_id,meetup_ref.id))

# send email notifications to all group members when a new meetup has been created
def send_meetup_create_notification(group, meetup, url):
  content = u"“"+group.name+u"”小组刚刚创建了一个新的碰头“"+meetup.topic+u"”（"+str(meetup.time_from)+u" - "+str(meetup.time_to)+u"），快来看看吧：\n"+url
  for user in group.users.all():
    async_send_mail(MEETUP_CREATE_EMAIL_SUBJECT, content, MEETUP_CREATE_EMAIL_FROM_ADDRESS, [user.email])
  return

def send_meetup_update_notification(group, meetup, old_topic, url):
  content = u"“"+group.name+u"”小组刚刚更新了您参加的碰头信息。\n"
  if not old_topic == meetup.topic:
    content += "原来的主题为："+old_topic + "现在的主题为："+meetup.topic + "\n"
  else:
    content +="碰头主题："+meetup.topic + "\n"
  content += "更新后的碰头时间是"+u":（"+str(meetup.time_from)+u" - "+str(meetup.time_to)+u"），快来看看吧：\n"+url
  #decide which user should receive this notice
  joinMeetups = JoinMeetup.objects.filter(meetup = meetup)
  for joinMeetup in joinMeetups:
    if joinMeetup.join_status == 0:
      user = joinMeetup.user
      async_send_mail("您参加的“"+group.name+"”小组"+ MEETUP_UPDATE_EMAIL_SUBJECT, content, MEETUP_UPDATE_EMAIL_FROM_ADDRESS, [user.email])


#update the existing meetup record
def update(request, meetup_id):

  upd_dict={}
  target_meetup = Meetup.objects.get(id=meetup_id)
  target_meetup.description = request.POST[u'description']
  target_meetup.address = request.POST[u'address']
  target_meetup.topic = request.POST[u'topic']
  date_from_list = request.POST[u'date_from'].split('/')
  date_from = date(int(date_from_list[2]), int(date_from_list[0]), int(date_from_list[1]))
  time_from_list = request.POST[u'time_from'].split(':')
  time_from = time(int(time_from_list[0]), int(time_from_list[1]))
  
  date_to_list = request.POST[u'date_to'].split('/')
  date_to = date(int(date_to_list[2]), int(date_to_list[0]), int(date_to_list[1]))
  time_to_list = request.POST[u'time_from'].split(':')
  time_to = time(int(time_to_list[0]), int(time_to_list[1]))
  
  datetime_from = datetime.combine(date_from, time_from)
  datetime_to = datetime.combine(date_to, time_to)
  target_meetup.time_from = datetime_from
  target_meetup.time_to = datetime_to
  
  upd_dict['topic'] = target_meetup.topic
  upd_dict['description'] = target_meetup.description
  upd_dict['address']=target_meetup.address
  upd_dict['date_from']=request.POST[u'date_from']
  upd_dict['time_from']=request.POST[u'time_from']
  upd_dict['date_to']=request.POST[u'date_to']
  upd_dict['time_to']=request.POST[u'time_to']
  
  target_meetup.save()
  return upd_dict
  
@permalink
def get_meetup_detail_url(group_id, meetup_id):
  return ('meet001.meetup.meetup_views.details', [group_id, meetup_id])
